package com.baidu.structure.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.baidu.structure.constants.Keys;
import com.baidu.structure.constants.Tables;
import com.baidu.structure.utils.ConfigUtils;

/**
 * Created by sunmo on 2016/12/1.
 */
public class DBHelper extends SQLiteOpenHelper {
    public static final int DB_VERSION = 1;
    private static DBHelper mDbHelper;
    private static final String PERSON_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + Tables.Person._TABLE_NAME + "(" +
            Tables.Person._USER_ID + " TEXT PRIMARY KEY," +
            Tables.Person._AVATAR + " TEXT" +
            ")";
    private static final String INVITE_INFO_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + Tables.InviteInfo._TABLE_NAME + "(" +
            Tables.InviteInfo._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            Tables.InviteInfo._NAME_FROM + " TEXT," +
            Tables.InviteInfo._AVATAR + " TEXT," +
            Tables.InviteInfo._DESC + " TEXT," +
            Tables.InviteInfo._WHEN + " TEXT," +
            Tables.InviteInfo._GROUP_ID + " TEXT," +
            Tables.InviteInfo._GROUP_NAME + " TEXT" +
            ")";

    //get db name
    private static String getDbName(Context context) {
        return ConfigUtils.getDefaultInstance(context).readString(Keys.LOGIN_NAME) + ".db";
    }

    //get db helper instance
    public static DBHelper getInstance(Context context) {
         if (mDbHelper==null){
             mDbHelper=new DBHelper(context,getDbName(context),null,DB_VERSION);
         }
        return mDbHelper;
    }

    private DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
          db.execSQL(PERSON_TABLE_CREATE);
          db.execSQL(INVITE_INFO_TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    //close db
    public void closeDb() {
        if (mDbHelper!=null){
            SQLiteDatabase db=mDbHelper.getWritableDatabase();
            db.close();
        }
        mDbHelper=null;
    }
}
